$(function () {
//	var hasP=hasPermission("iqc:user:sqe");
    $("#jqGrid").jqGrid({
        url: '../beer/list',
        datatype: "json",
        colModel: [
			{ label: '啤模编号', name: 'bEERMOLDID', width: 80,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15} }, 			
			{ label: '啤模名称', name: 'bEERMOLDNAME', width: 80,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}  }, 			
			{ label: '客户编号', name: 'cUSTOMERID', width: 80 ,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}}, 			
			{ label: '客户名称', name: 'cUSTOMERCODE', width: 80,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}  }, 			
			{ label: '货号', name: '', width: 80 ,hidden:true,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}}, 			
			{ label: '纸质', name: 'qUALITY', width: 80 ,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}},
			{ label: '用料（宽）', name: 'uSEWIDTH', width: 80 ,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}},
			{ label: '用料（长）', name: 'uSELENGTH', width: 80 ,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}},
			{ label: '单位', name: 'uNITID', width: 80 ,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}},
			{ label: '单位比率', name: 'uNITEXCH', width: 80 ,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}},
			{ label: '一模成型数量', name: 'qUANTITY', width: 80 ,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}},
			{ label: '每箱用料比例', name: 'uNITQUANTITY', width: 80 ,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}},
			{ label: '存放位置', name: 'pLACE', width: 80 ,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}},
			{ label: '组件编号', name: 'pARENTBEERMOLDID', width: 80 ,editable:true, edittype:"text", editrules:{required: true},editoptions:{size:16, maxlength: 15}},
			{ label: 'oldDataFlag', name: 'oldDataFlag', width: 80,hidden:true }
        ],
		viewrecords: true,
		cellEdit: false,
		cellsubmit: "clientArray", //当单元格发生变化后不直接发送请求、"remote"默认直接发送请求
        height: 400,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		bEERMOLDID: null,
		cUSTOMERCODE: null,
		editFlag: 0,    //0:初始状态        1：新增状态         2：编辑状态
		addNewRows: 0
	},
	methods: {
		update: function (supplierId) {
			if(supplierId == null){
				return ;
			}
			
			location.href = "iqcsupplierbaseinfot_add.html?supplierId="+supplierId;
		},
		exportBeerMoldExcel: function(){
    		var url="../beer/exportBeerMoldExcel";
            var elemIF = document.createElement("iframe");   
            elemIF.src = url;   
            elemIF.style.display = "none";   
            document.body.appendChild(elemIF);   
            
		},
		unImportEdit: function(){
			this.editFlag=0;
			
		},
		importEdit: function(){
			this.editFlag=3;
			
		},
		importBeerMoldExcel: function(){
			var this_=this;
			var formParam = {};
			var da =  new FormData();
			var file = document.querySelector(  'input[type=file]').files[0];
//            if(file!=undefined){
//            	formParam.fileName=file.name;
//            	var size = file.size;
//            	if(size>10485760){
//            		this_.$message({
//		                type: 'warning',
//		                message: '附件大小不能超过10M!'
//		            });
//            		return;
//            	}
//            }
//            da.append("formParam", JSON.stringify(formParam));

            da.append("file", file);

            console.log(da);

            $.ajax({
                url: '../beer/importBeerMoldExcel',
                type: 'post',
                data: da,
                dataType: "json",
                cache: false,
                processData: false,
                contentType: false,
                // async: false
            }).done(function (res) {
            	if(res.code==0){
            		alert('导入成功：'+res.import, function(index){
						vm.query();
					});
            	}else{
            		var errorList="";
            		for(var i=0;i<res.list.length;i++){
            			errorList+=res.list[i]+";"
            		}
            		alert('保存失败!'+res.msg+":"+errorList);
            	}
            }).fail(function (res) {
                console.log(res);
                alert(res.msg);
                
            });
            
		},
		add: function(){
			this.editFlag=1;
			this.addNewRows++;
			 //要添加的jqgrid中的行数据
		    var dataRow = {
		        "bEERMOLDID" : "<input name='bEERMOLDID' id='"+this.addNewRows+"_bEERMOLDID' placeholder='啤模编号' type='text' >",
		        "bEERMOLDNAME" : "<input name='bEERMOLDNAME' id='"+this.addNewRows+"_bEERMOLDNAME' placeholder='啤模名称' type='text' >",
		        "cUSTOMERID" : "<input name='cUSTOMERID' id='"+this.addNewRows+"_cUSTOMERID'  placeholder='客户编号' type='text'>",
		        "cUSTOMERCODE" : "<input name='cUSTOMERCODE' id='"+this.addNewRows+"_cUSTOMERCODE'  placeholder='客户名称' type='text' >",
		        "qUALITY" : "<input name='qUALITY' id='"+this.addNewRows+"_qUALITY'  placeholder='纸质' type='text'>",
		        "uSEWIDTH" : "<input name='uSEWIDTH' id='"+this.addNewRows+"_uSEWIDTH' placeholder='用料（宽）' type='text' >",
		        "uSELENGTH" : "<input name='uSELENGTH' id='"+this.addNewRows+"_uSELENGTH' placeholder='用料（长）' type='text' >",
		        "uNITID" : "<select name='uNITID' id='"+this.addNewRows+"_uNITID' ><option>MM</option><option>INCH</option><option>CM</option> </select>",
		        "uNITEXCH" : "<input name='uNITEXCH' id='"+this.addNewRows+"_uNITEXCH' placeholder='单位比率' type='text' >",
		        "qUANTITY" : "<input name='qUANTITY' id='"+this.addNewRows+"_qUANTITY'  placeholder='一模成型数量' type='text' >",
		        "uNITQUANTITY" : "<input name='uNITQUANTITY' id='"+this.addNewRows+"_uNITQUANTITY'  placeholder='每箱用料比例' type='text' >",
		        "pLACE" : "<input name='pLACE' id='"+this.addNewRows+"_pLACE'  placeholder='存放位置' type='text' >",
		        "pARENTBEERMOLDID" : "<input name='pARENTBEERMOLDID' id='"+this.addNewRows+"_pARENTBEERMOLDID'  placeholder='组件编号' type='text' >",
		        "oldDataFlag" : "false"
		    };
		    var rowIds = jQuery("#jqGrid").jqGrid('getDataIDs');//获取jqgrid中所有数据行的id
		    for(var i=0;i<rowIds.length;i++){
				rowData = $("#jqGrid").jqGrid("getRowData",rowIds[i]);
				if(rowData.oldDataFlag == 'true') {
					$("#jqGrid").jqGrid("delRowData", rowIds[i]);//设置该行不能被选中。
				}
			}
		    //使用addRowData方法把dataRow添加到表格中
		    $("#jqGrid").jqGrid("addRowData",this.addNewRows , dataRow, "first"); 
		},
		saveOrUpdate: function (paramData,type) {
			var url = type == "save" ? "../beer/save" : "../beer/update";
			$.ajax({
				type: "POST",
			    url: url,
			    data: JSON.stringify(paramData),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.query();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (type) {
			var bEERMOLDIDs=[];
//			var allData = $("#jqGrid").jqGrid("getRowData"); *****   少第一行   bug!
			var roleIds = getSelectedRows();
			if(roleIds == null){
				return ;
			}
			if(type==1){
				var selectedRowIds =  $("#jqGrid").jqGrid("getGridParam","selarrrow");  
				var len = selectedRowIds.length;  
				for(var i = 0;i < len ;i ++) {  
					$("#jqGrid").jqGrid("delRowData", selectedRowIds[0]);  
				}  
			}else{
				for(var i=0;i<roleIds.length;i++){
					var rowData = $("#jqGrid").jqGrid('getRowData',roleIds[i]);
					bEERMOLDIDs.push(rowData.bEERMOLDID);
				}
				confirm('确定要删除选中的记录？', function(){
					$.ajax({
						type: "POST",
					    url: "../beer/delete",
					    data: JSON.stringify(bEERMOLDIDs),
					    success: function(r){
							if(r.code == 0){
								alert('操作成功', function(index){
									$("#jqGrid").trigger("reloadGrid");
								});
							}else{
								alert(r.msg);
							}
						}
					});
				});
			}
		},
		query: function () {
			this.editFlag=0;
			$("#jqGrid").jqGrid('setGridParam',{ 
                postData:{
                	'bEERMOLDID': vm.bEERMOLDID,
                	'cUSTOMERCODE': vm.cUSTOMERCODE
                	},
                page:1 
            }).trigger("reloadGrid");
		},
		reset: function () {
			vm.bEERMOLDID=null;
			vm.cUSTOMERCODE=null;
			vm.query();
		},
		saveCellEdit: function(){
			var rowIds = jQuery("#jqGrid").jqGrid('getDataIDs');//获取jqgrid中所有数据行的id
			var newData = [];
		    for(var i=0;i<rowIds.length;i++){
				rowData = $("#jqGrid").jqGrid("getRowData",rowIds[i]);
				var dataRow = {
				        "bEERMOLDID" : this.getRealValue(rowData["bEERMOLDID"]),
				        "bEERMOLDNAME" : this.getRealValue(rowData["bEERMOLDNAME"]),
				        "cUSTOMERCODE" : this.getRealValue(rowData["cUSTOMERCODE"]),
				        "cUSTOMERID" : this.getRealValue(rowData["cUSTOMERID"]),
				        "qUALITY" : this.getRealValue(rowData["qUALITY"]),
				        "uSEWIDTH" : this.getRealValue(rowData["uSEWIDTH"]),
				        "uSELENGTH" : this.getRealValue(rowData["uSELENGTH"]),
				        "uNITID" : this.getRealValue(rowData["uNITID"]),
				        "uNITEXCH" : this.getRealValue(rowData["uNITEXCH"]),
				        "qUANTITY" : this.getRealValue(rowData["qUANTITY"]),
				        "uNITQUANTITY" : this.getRealValue(rowData["uNITQUANTITY"]),
				        "pLACE" : this.getRealValue(rowData["pLACE"]),
				        "pARENTBEERMOLDID" : this.getRealValue(rowData["pARENTBEERMOLDID"]),
				        "bEERMOLDLEVEL": 1
				    };
				newData.push(dataRow);
		    }
			console.log(newData);
			this.saveOrUpdate(newData,"save");
			//alert("save success");
		},
		updateCellEdit: function(){
			var selectedRowIds =  $("#jqGrid").jqGrid("getGridParam","selarrrow");  
			console.log(selectedRowIds);
			var newData = [];
		    for(var i=0;i<selectedRowIds.length;i++){
//				rowData = $("#jqGrid").jqGrid("getRowData",selectedRowIds[i]);
				var dataRow = {
				        "bEERMOLDID" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "bEERMOLDID")),
				        "bEERMOLDNAME" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "bEERMOLDNAME")),
				        "cUSTOMERCODE" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "cUSTOMERCODE")),
				        "cUSTOMERID" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "cUSTOMERID")),
				        "qUALITY" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "qUALITY")),
				        "uSEWIDTH" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "uSEWIDTH")),
				        "uSELENGTH" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "uSELENGTH")),
				        "uNITID" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "uNITID")),
				        "uNITEXCH" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "uNITEXCH")),
				        "qUANTITY" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "qUANTITY")),
				        "uNITQUANTITY" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "uNITQUANTITY")),
				        "pLACE" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "pLACE")),
				        "pARENTBEERMOLDID" : this.getRealValue($("#jqGrid").getCell(selectedRowIds[i], "pARENTBEERMOLDID"))
				    };
				newData.push(dataRow);
		    }
			this.saveOrUpdate(newData,"update");
			//alert("save success");
		},
		getRealValue: function(pValue) {
            if (/msie/.test(navigator.userAgent.toLowerCase())) {
                var oReg2 = /(\s+\w+=)('|")?(.*?)('|")?(?=\s+\w+=|\s*>|\s*\/>)/gi;
                pValue = pValue.replace(oReg2, "$1\"$3\"");
                var oReg = /^<(input|INPUT).*id=\"(.*?)\"/m;
                var val = pValue.match(oReg);
                return !val ? pValue : $("#" + val[2]).val();
            }
            else {
                var regExp = /^<.*? id=['"](.*?)['"].*?>$/;
                var val = pValue.match(regExp);
                return !val ? pValue : $("#" + val[1]).val();
            }
        },
		cancelCellEdit: function(){
			this.query();
		},
		openCellEdit: function(){
			var roleIds = getSelectedRows();
			if(roleIds == null){
				return ;
			}
			for(var i=0;i<roleIds.length;i++){
				$("#jqGrid").jqGrid('editRow',roleIds[i],true);
				this.editFlag=2;
			}
			
		}
	}
});

